package com.dcy.znoa.controller.attendance;

import com.dcy.znoa.common.annotation.AuthenticationAPI;
import com.dcy.znoa.common.controller.BaseController;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.DateTimeUtil;
import com.dcy.znoa.common.util.DateUtil;
import com.dcy.znoa.common.util.excel.ExcelOutput;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.attendance.model.attRealRecord.*;
import com.dcy.znoa.domain.attendance.ArrAndApplyVo;
import com.dcy.znoa.service.attendance.AttRealRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;

/**
 * 员工考勤真实记录表
 *
 * @author pengyu
 */
@Controller
@RequestMapping("attRealRecord")
public class AttRealRecordController extends BaseController {

    @Autowired
    AttRealRecordService attRealRecordService;

    //APP 日历方式查看考勤记录（只查询异常列表，查询结果是时间列表），根据用户id和时间跨度来查询异常记录，方便APP标红和标蓝
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryReasonList")
    public JsonForList queryReasonList(@Valid SelectAbnormalARRModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return new JsonForList("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List list = attRealRecordService.queryReasonList(model);
        return new JsonForList(list);
    }

    //APP 单人单日考勤及申请或异常集合查询（结果是考勤记录列表，每一天是两条数据）：点击当月考勤记录中某日后，调用此接口来查询
    // PS:也可以作为通用接口
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryList")
    public JsonForList queryList(@Valid SelectARRModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return new JsonForList("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List list = attRealRecordService.queryList(model);
        return new JsonForList(list);
    }

    //APP 1.6.1，单人：带统计(对应原型：考勤统计-个人统计) 正常 迟到 早退 未打卡 地点异常 请假 出差 外勤  8种汇总的次数
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryGroup")
    public JsonForList queryGroup(@Valid SelectAbnormalARRModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        List list = attRealRecordService.queryGroup(model);
        return new JsonForList(list);
    }

    //APP 单人：查询某一种考勤类型的时间列表：按开始和结束时间来查询（年月日）;考勤汇总考虑做通用接口：开始时间、结束时间、用户id)
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryTimesByAttTypeAndOper")
    public JsonForList queryTimesByTypeAndOper(@Valid SelectTimebyAttTypeModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return new JsonForList("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List list = attRealRecordService.queryTimesByAttTypeAndOper(model);
        return new JsonForList(list);
    }

    //APP 单人：查询某一种申请类型的时间列表：按开始和结束时间来查询（年月日）;考勤汇总考虑做通用接口：开始时间、结束时间、用户id)
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryTimesByApplyTypeAndOper")
    public JsonForList queryTimesByApplyTypeAndOper(@Valid SelectTimebyApplyTypeModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return new JsonForList("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List list = attRealRecordService.queryTimesByApplyTypeAndOper(model);
        return new JsonForList(list);
    }

    //APP 按单项数量查询对应人列表  条件：部门ID+ 公司ID 考勤类别+ 时间
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryOpersByAttType")
    public JsonForList queryOpersByAttType(@Valid QueryOpersByAttTypeModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return new JsonForList("404", bindingResult.getFieldError().getDefaultMessage());
        }
        if (model.getCompId() == null) {
            model.setCompId(getCurrentUser().getCompId());
        }
        List list = attRealRecordService.queryOpersByAttType(model);
        return new JsonForList(list);
    }

    //APP 按单项数量查询对应人列表  条件：部门ID+ 公司ID 申请类别+ 时间
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryOpersByApplyType")
    public JsonForList queryOpersByApplyType(@Valid QueryOpersByApplyTypeModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return new JsonForList("404", bindingResult.getFieldError().getDefaultMessage());
        }
        if (model.getCompId() == null) {
            model.setCompId(getCurrentUser().getCompId());
        }
        List list = attRealRecordService.queryOpersByApplyType(model);
        return new JsonForList(list);
    }

    //WEB 考勤汇总-搜索
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryAttAndApplyGroup")
    public JsonForList queryAttAndApplyGroup(@Valid QueryAttAndApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        return attRealRecordService.queryAttAndApplyGroup(model);
//        return new JsonForList(list);
    }

    //WEB 考勤汇总-查看打卡详情
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryAttDetailAllDay")
    public JsonForList queryAttDetailAllDay(@Valid QueryAttAndApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        return attRealRecordService.queryAttDetailAllDay(model);
//        return new JsonForList(list);
    }

    //WEB 考勤汇总-搜索-导出
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/export")
    public JsonCommon export(@Valid QueryAttAndApplyModel model, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws BusinessException, InvocationTargetException, IllegalAccessException, IOException {
        if (bindingResult.hasErrors()) {
            return new JsonCommon("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List<Map<String, Object>> recordList = new ArrayList<>();
//        List<ArrAndApplyVo> list = attRealRecordService.queryAttAndApplyGroup(model);
        JsonForList jsonForList = attRealRecordService.queryAttAndApplyGroup(model);
        List<ArrAndApplyVo> list = jsonForList.getData();
//        Map<String, Object> map = new HashMap<>();//list转map
//        for (int i = 0; i < list.size(); i++) {
//            map.put(String.valueOf(i),list.get(i));
//            recordList.add((Map<String, Object>) list.get(i));
//        }
        for (ArrAndApplyVo arrAndApplyVo : list) {
            recordList.add(ArrAndApplyVo.toMap(arrAndApplyVo));
        }

//        recordList.add(map);

        String keys[] = {"depName", "operName", "phoneNo", "normal", "late",      "leaveEarly", "addAbnormal", "notHit",       "appTravel", "appOut", "appLeave"};//map中的key
        String columnNames[] = {"部门", "姓名", "联系方式", "正常（次）", "迟到（次）", "早退（次）", "地点异常（次）", "未打卡（次）", "出差（次）", "外勤（次）", "请假（次）"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "考勤汇总");
        return new JsonCommon(SUCCESS_CODE);
    }

    //WEB 打卡详情-搜索-导出
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/exportAttDetailAllDay")
    public JsonCommon exportAttDetailAllDay(@Valid QueryAttAndApplyModel model, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws BusinessException, InvocationTargetException, IllegalAccessException, IOException {
        if (bindingResult.hasErrors()) {
            return new JsonCommon("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List<Map<String, Object>> recordList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();//list转map
//        List list = attRealRecordService.queryAttDetailAllDay(model);
        JsonForList jsonForList = attRealRecordService.queryAttDetailAllDay(model);
        List list = jsonForList.getData();
        for (int i = 0; i < list.size(); i++) {
//            map.put(String.valueOf(i),list.get(i));
            recordList.add((Map<String, Object>) list.get(i));
        }
//        recordList.add(map);

        String keys[] = {"att_time", "dep_name", "oper_name", "phone_no", "up_time", "up_hit_type_str", "up_address","up_audit_str", "down_time", "down_hit_type_str", "down_address", "down_audit_str"};//map中的key
        String columnNames[] = {"日期", "部门", "姓名", "联系方式", "上班", "打卡类型", "异常地点", "申述状态", "下班", "打卡类型", "异常地点", "申述状态"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "考勤汇总");
        return new JsonCommon(SUCCESS_CODE);

    }

    //APP 通过某一天的时间 eg:2018-02-03 来查询这一天对应的申请和申述信息
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryOneDayApply")
    public JsonForList queryOneDayApply(@Valid String dateStr,Long operId) throws BusinessException, InvocationTargetException, IllegalAccessException {
        Date date = DateTimeUtil.StrDateToDate(dateStr);

        List list = attRealRecordService.queryOneDayApply(dateStr,operId);
        return new JsonForList(list);
    }

}
